package com.tt.job.zookeeper;

import com.tt.job.api.Job;
import com.tt.job.register.JobChangeListener;
import com.tt.job.util.JobUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZookeeperJobChangeExecutor implements PathChildrenCacheListener {
    private final static Logger logger = LoggerFactory.getLogger(ZookeeperJobChangeExecutor.class);

    private final JobChangeListener listener;

    public ZookeeperJobChangeExecutor(JobChangeListener listener) {
        this.listener = listener;
    }

    @Override
    public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
        if (event.getData() == null) {
            return;
        }
        String path = event.getData().getPath();
        path = path.substring(path.lastIndexOf('/') + 1);
        String[] jobInfos = path.split("-");
        switch (event.getType()) {
            case CHILD_ADDED:
                //job节点添加
                if (jobInfos.length != 2) {
                    logger.warn("zookeeper job path is error. path:{}", path);
                    return;
                }
                String jobClass = jobInfos[1];
                String jobType = jobInfos[0];
                Job job = JobUtils.getJobInstance(jobType, jobClass, event.getData().getData());
                if (job != null) {
                    listener.notifyJobAdded(jobClass, job);
                } else {
                    logger.warn("zookeeper add job info is null");
                }
                break;
            case CHILD_REMOVED:
                if (jobInfos.length != 2) {
                    logger.warn("zookeeper job path is error. path:{}", path);
                    return;
                }
                jobClass = jobInfos[1];
                listener.notifyJobDeleted(jobClass);
                break;
            case CHILD_UPDATED:
                if (jobInfos.length != 2) {
                    logger.warn("zookeeper job path is error. path:{}", path);
                    return;
                }
                jobClass = jobInfos[1];
                jobType = jobInfos[0];
                job = JobUtils.getJobInstance(jobType, jobClass, event.getData().getData());
                if (job != null) {
                    listener.notifyJobChanged(jobClass, job);
                } else {
                    logger.warn("zookeeper update job info is null");
                }
                break;
        }
    }
}
